<template>
  <div class="app-container">
    <!-- 订单详情 -->
    <div class="order-info">
      <el-col v-if="purchaseOrder.orderState == '-1'"><div class="bg-red" style="padding-bottom: 10px;padding-left: 50px;">驳回理由：{{ purchaseOrder.pOrderAuditComment }}</div></el-col>
      <el-card v-loading="orderInfoLoading" class="box-card">
        <el-row>
          <el-col :span="10" :offset="2">单据编号：{{ purchaseOrder.pOrderNo }}</el-col>
          <el-col :span="10" :offset="2">状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;态：{{ purchaseOrder.orderState | formatStatus }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="10" :offset="2">仓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库：{{ purchaseOrder.warehouseName }}</el-col>
          <el-col :span="10" :offset="2">创建时间：{{ purchaseOrder.gmtCreate | formatDateAndTime }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="10" :offset="2">操&nbsp;&nbsp;作&nbsp;&nbsp;人：{{ purchaseOrder.adminRealname }}</el-col>
          <el-col :span="10" :offset="2">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注：{{ purchaseOrder.pOrderInfo }}</el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 入库详情 -->
    <div class="p-order-goods-info" >
      <el-col :span="6"><div >供应商：{{ purchaseOrder.supplierName }}</div></el-col>
      <el-col :span="6"><div >商品总额：{{ purchaseOrder.pOrderGoodsAmount }}元</div></el-col>
      <div class="p-order-goods-list">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="dataForm"
          status-icon
          label-position="left"
          label-width="100px"
        >
          <el-table
            v-loading="pOrderGoodsLoading"
            :data="pOrderGoodsList"
            size="small"
            element-loading-text="正在查询中。。。"
            border
            fit
            highlight-current-row
            style="white-space: pre-line;"
          >
            <el-table-column align="center" label="商品" prop="goodsName" width="200px" style="display: inline-block;">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.goodsImg + '?x-oss-process=style/100px'" width="40" ></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.goodsName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column prop="goodsUnit" align="center" label="单位" width="60px"/>
            <el-table-column align="center" label="条形码" prop="barCode" />
            <el-table-column align="center" label="计划数量" prop="pGoodsBuyNum" />
            <el-table-column align="center" label="实际数量" prop="pGoodsActualNum" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.pGoodsActualNum" placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="总金额" prop="pGoodsAmount" width="150px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.pGoodsAmount" placeholder=""/>
              </template>
            </el-table-column>
          </el-table>

        </el-form>
        <div v-if="purchaseOrder.orderState != 2" slot="footer" class="dialog-footer">
          <el-button type="primary" @click="createData(0)">部分确认</el-button>
          <el-button type="primary" @click="createData(2)">全部确认(同时生成入库单)</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<style>
  .bg-red {
    color: #F56C6C;
  }
  .order-info .el-row {
    margin-bottom: 20px;
  }
  .p-order-goods-info {
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .p-order-goods-list{
    padding-top: 40px;
  }

</style>
<script>
import { detail, updateConform } from '@/api/purchaseorder'
import { formatDateAndTime } from '@/filters'
export default {
  name: 'PurchaseOrderDetail',
  components: {},
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return '无'
      }
      return formatDateAndTime(time)
    },
    formatStatus(status) {
      if (status === 1) {
        return '已采购'
      } else if (status === 0) {
        return '待采购'
      } else if (status === -1) {
        return '驳回'
      }
    }
  },
  data() {
    return {
      purchaseOrder: {
        id: this.$route.query.pOrderId,
        pOrderNo: undefined,
        gmtCreate: ''
      },
      dataForm: {
        id: this.$route.query.pOrderId,
        purchaseOrderGoodsDTOS: [],
        orderState: 0,
        totalPrice: 0,
        total: 0,
        warehouseId: undefined,
        warehouseIsSelected: true,
        pOrderConpon: 0,
        supplierInfo: {},
        supplierName: undefined,
        supplierId: undefined
      },
      pOrderId: this.$route.query.pOrderId,
      pOrderGoodsLoading: true,
      pOrderGoodsList: [],
      pOrderLogsLoading: true,
      pOrderLogsList: [],
      selectSpuList: [],
      orderInfoLoading: true
    }
  },
  computed: {
    selSpuListTotalPrice: function() {
      let totalPrice = 0
      for (let i = 0; i < this.pOrderGoodsList.length; i++) {
        if (this.pOrderGoodsList[i].pGoodsAmount && new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(this.pOrderGoodsList[i].pGoodsAmount)) {
          totalPrice += parseFloat(this.pOrderGoodsList[i].pGoodsAmount)
        }
      }
      return Math.round(totalPrice * 100) / 100
    }
  },
  created() {
    this.orderDetail()
  },
  methods: {
    orderDetail() {
      this.pOrderGoodsLoading = true
      this.pOrderLogsLoading = true
      this.orderInfoLoading = true
      detail(this.purchaseOrder).then(response => {
        this.purchaseOrder = response.data.data
        this.pOrderGoodsLoading = false
        this.pOrderLogsLoading = false
        this.orderInfoLoading = false
        this.pOrderGoodsList = this.purchaseOrder.purchaseOrderGoodsDTOS
      }).catch(response => {
        this.pOrderGoodsLoading = false
        this.pOrderLogsLoading = false
        this.orderInfoLoading = false
        this.$notify.error({
          title: '失败',
          message: '没有此采购单'
        })
      })
    },
    goBackList() {
      this.$router.push({ path: '/purchase/purchaselist' })
    },
    createData(status) {
      if (status === 0) {
        const selectSpuList = this.pOrderGoodsList
        let goodNumValid = true
        let goodnumvalue = ''
        let goodPriceValid = true
        let goodValuePrice = ''
        for (let i = 0; i < selectSpuList.length; i++) {
          if (!new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(selectSpuList[i].pGoodsActualNum)) {
            goodNumValid = false
            goodnumvalue = selectSpuList[i].goodsName
            break
          }
          if (!new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(selectSpuList[i].pGoodsAmount)) {
            goodPriceValid = false
            goodValuePrice = selectSpuList[i].goodsName
            break
          }
        }
        if (!goodNumValid) {
          this.$notify({
            title: '提示',
            message: `请核对${goodnumvalue}实际数量`,
            type: 'warning'
          })
        } else if (!goodPriceValid) {
          this.$notify({
            title: '提示',
            dangerouslyUseHTMLString: true,
            message: `${goodValuePrice}总价核对格式)`,
            type: 'warning'
          })
        } else {
          this.dataForm.purchaseOrderGoodsDTOS = selectSpuList
          this.dataForm.orderState = status
          this.dataForm.totalPrice = this.selSpuListTotalPrice
          this.optloading = true
          updateConform(this.dataForm)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '保存成功'
              })
            })
            .catch(response => {
              this.optloading = false
              this.$notify.error({
                title: '失败',
                message: '失败'
              })
            })
        }
        return
      }
      const selectSpuList = this.pOrderGoodsList
      let isHasEmptyValue = false
      let isHasEmpValue = ''
      let goodNumValid = true
      let goodnumvalue = ''
      let goodPriceValid = true
      let goodValuePrice = ''
      for (let i = 0; i < selectSpuList.length; i++) {
        if (!selectSpuList[i].pGoodsActualNum || !selectSpuList[i].pGoodsAmount) {
          isHasEmptyValue = true
          isHasEmpValue = selectSpuList[i].goodsName
          break
        }
        if (!new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(selectSpuList[i].pGoodsActualNum)) {
          goodNumValid = false
          goodnumvalue = selectSpuList[i].goodsName
          break
        }
        if (!new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(selectSpuList[i].pGoodsAmount)) {
          goodPriceValid = false
          goodValuePrice = selectSpuList[i].goodsName
          break
        }
        selectSpuList[i].pGoodsPrice = Math.round((selectSpuList[i].pGoodsAmount * 100 / selectSpuList[i].pGoodsBuyNum)) / 100
      }
      if (selectSpuList.length === 0) {
        this.$notify.error({
          title: '失败',
          message: '请选择商品'
        })
        return
      } else if (isHasEmptyValue) {
        this.$notify.error({
          title: '失败',
          message: `请核对${isHasEmpValue}商品实际数量和金额`
        })
        return
      } else if (!goodNumValid) {
        this.$notify({
          title: '提示',
          message: `${goodnumvalue}实际数量请填写1到3位小数`,
          type: 'warning'
        })
      } else if (!goodPriceValid) {
        this.$notify({
          title: '提示',
          dangerouslyUseHTMLString: true,
          message: `${goodValuePrice}金额请填写整数或者两位小数`,
          type: 'warning'
        })
        return
      } else {
        this.dataForm.purchaseOrderGoodsDTOS = selectSpuList
        this.dataForm.orderState = status
        this.dataForm.totalPrice = this.selSpuListTotalPrice
        this.optloading = true
        updateConform(this.dataForm)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '保存成功'
            })
            this.$router.push({ path: '/purchase/purchaselist' })
          })
          .catch(response => {
            this.optloading = false
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }
    }
  }
}
</script>
